package com.dyh.quickdemo.demos.cdAndFail;

import lombok.SneakyThrows;
import lombok.Synchronized;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
@Author=Joey Wheeler
@Date=2020/10/21 17:56
*/
public class CdAndFail {

    @Test
    public void test() {
//        List<MyThread> myThreads = Lists.newArrayList(
//                new MyThread(1000L),
//                new MyThread(2000L),
//                new MyThread(1500L),
//                new MyThread(1000L),
//                new MyThread(1145L)
//        );
        List<Long> times = Lists.newArrayList(
                1000L,
                2000L,
                1500L,
                500L,
                1000L,
                500L
        );
        CountDownLatch countDownLatch = new CountDownLatch(times.size());

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //List<Integer> failIds = new ArrayList<>();
        List<Integer> failIds = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < times.size(); i++) {
            long delay = times.get(i);
            int finalI = i;
            executorService.execute(() -> {
                try {
                    if (delay <1000)
                        throw new RuntimeException("<1000");
                    try {
                        Thread.sleep(delay);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (RuntimeException e) {
                    failIds.add(finalI);
                }
                finally {
                    countDownLatch.countDown();
                }
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
    }
}
